package com.mrobuy.jd.productline;

import com.gavel.database.SQLExecutor;
import com.mrobuy.jdvc.entity.VCCateBrand;
import com.mrobuy.jdvc.entity.VCCategory;
import com.mrobuy.util.MD5Utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;

public class ProductlineBarndParser {

    public static void main(String[] args) throws IOException {
        parser("wysgyp");
    }

    public static void parser(String vendor) throws IOException {

        File dataFile =  new File("productline_" + vendor + ".html");
        if ( !dataFile.exists() ) {
            throw new FileNotFoundException(dataFile.getAbsolutePath());
        }


        byte[] data = Files.readAllBytes(dataFile.toPath());

        String html = new String(data);

        Document doc = Jsoup.parse(html);

        Elements rows = doc.select("tr");
        for (Element row : rows) {
            Elements tds = row.select("td");
            if ( tds == null || tds.size() < 5 ) {
                continue;
            }

            String cateName = tds.get(3).text();
            String brandInfo = tds.get(4).text();

            brandInfo = brandInfo.replace("]", "");

            String[] arr = brandInfo.split("\\[");


            VCCategory vcCategory = null;
            try {
                vcCategory =  SQLExecutor.executeQueryBean("select * from VC_CATEGORY where NAME = ? ", VCCategory.class, cateName);
            } catch (Exception e) {

                e.printStackTrace();
            }

            if ( vcCategory==null ) {
                System.out.println("cateName: " + cateName + " is null");
                continue;
            }

            VCCateBrand record = new VCCateBrand();
            record.setCateid(vcCategory.getId());
            record.setCatename(vcCategory.getName());
            record.setBrandid(Integer.parseInt(arr[1]));
            record.setName(arr[0]);
            record.setStatus("N");
            if ( tds.get(10)!=null && "已生效".equalsIgnoreCase( tds.get(10).text())  ) {
                record.setStatus("Y");
            }
            record.setAccount(vendor);
            record.setId(MD5Utils.md5Hex(record.getCateid() + "_" + record.getBrandid()));

            try {

                VCCateBrand exist = SQLExecutor.executeQueryBean("select * from VC_CATE_BRAND where ID = ? ",  VCCateBrand.class,  record.getId());
                if ( exist == null ) {
                    SQLExecutor.insert(record);
                } else {
                    SQLExecutor.update(record, false);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            System.out.println(vcCategory.getName() + ": " + arr[0] + ", " + arr[1]);

        }

        System.out.println(html.substring(0, 100));
    }
}
